# -*- coding: UTF-8 -*-
import json
from os import close
import time
from tkinter.constants import RIGHT, W, Y, E # 空间布局方位
import requests
import tkinter as tk
import webbrowser
import tkinter.ttk as ttk # 分页栏
from tkinter import messagebox
base_url = "http://www.ccgp-xinjiang.gov.cn"
url = "http://www.ccgp-xinjiang.gov.cn/front/search/category"


class TestBenchMaker:
    def __init__(self):
        self.TITLE = "新疆政府采购网招标公告"
        self.WIDTH = 1500
        self.HEIGHT = 900
        self.parseDic = {}

# Initial GUI
    def initialGUI(self):
        window = tk.Tk()
        window.title(self.TITLE)
                
        # 界面显示在屏幕中心
        self.ws = window.winfo_screenwidth()
        self.hs = window.winfo_screenheight()
        x = (self.ws / 2) - (self.WIDTH / 2)
        y = (self.hs / 2) - (self.HEIGHT / 2)
        window.geometry('%dx%d+%d+%d' % (self.WIDTH, self.HEIGHT, x, y))
        window.resizable(0, 0)
        # post请求参数设置       
        def post_url(payloadData):
            timeout = 25
            # 设置代理
            proxy = '222.74.202.229:8080'
            proxies = {
                'http': 'http://' + proxy,
                'https': 'https//' + proxy
            }
            # 请求头设置
            headers = {
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67",
                        "Host": "www.ccgp-xinjiang.gov.cn",
                        "Content-Type": "application/json;charset=UTF-8"}
            # Json解析
            dumpJsonData = json.dumps(payloadData)
            # 打印解析信息
            # print(f"dumpJsonData = {dumpJsonData}")
            res = requests.post(url, data=dumpJsonData, headers=headers, proxies=proxies, timeout=timeout,  allow_redirects=True)
            return res
        # 清洗数据，获得字典类型数据
        def clear_data(res):
            html = res.content.decode('utf8')
            html_dic = json.loads(html)
            dic_data = html_dic["hits"]
            final_datas = dic_data["hits"]
            return final_datas

        names = locals() # 创建动态变量功能
        tab = ttk.Notebook(window)  # 创建分页栏
        frame1 = tk.Frame(tab)
        ''' 
        **********第一页最新公告**********
        '''
        tab.add(frame1, text='最新公告') 
        style = ttk.Style()
        style.configure('TNotebook.Tab', font=('URW Gothic L', '15', 'bold'), padding=[10, 10])
        text1 = tk.Text(frame1, width=161, height=46, font=("URW Gothic L", 13))
        text1.grid(row=2, columnspan=50, sticky=W, padx=20, pady=20)
        # 45条最新公告
        for i in range(1, 4):
            names["payloadData%s" % i] = {
                    'categoryCode': "ZcyAnnouncement2",
                    'pageNo': f'{i}',
                    'pageSize': 15}

            names["res%s" % i] = post_url(names["payloadData%s" % i])
            final_datas = clear_data(names["res%s" % i])
            j = (i-1)*15+1
            for final_data in final_datas:
                data = final_data['_source']
                names["timeStamp_%s" % j] = int(data['publishDate']/1000)
                # timeStamp_2 = int(data['bidOpeningTime']/1000)
                names["timeArrays_%s" % j] = time.localtime(names["timeStamp_%s" % j])
                # timeArrays_2 = time.localtime(timeStamp_2)
                publishDate = time.strftime("%Y--%m--%d %H:%M:%S", names["timeArrays_%s" % j])
                # bidOpeningTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArrays_2)
                districtName = data['districtName'].replace("新疆维吾尔自治区本级", '', 1)
                title = (data['title'])
                f_url = (base_url + data['url'])
                if title:
                    text1.tag_config('link>' + f_url, underline=True)
                    text1.insert('insert', "【" + publishDate + "】" + title + '\n' + '\n', 'link>' + f_url)
                    text1.tag_bind('link>' + f_url, "<Double-Button-1>",
                                lambda event, f_url=f_url: open_url(event, f_url))
                else:
                    text1.insert('insert', "加载完成！！！")
                # 鼠标左键双击点击打开网页时间绑定
                def open_url(event, f_url):
                    webbrowser.open(f_url, new=0)

        '''
        **********第二页 公告查询功能**********
        '''
        frame2 = tk.Frame(tab)
        tab.add(frame2, text="公告查询")
                    
        def func():
            text.delete('0.0', 'end')
            val = entry.get()
            # 关键字提交信息
            for i in range(1, 11):   # 最多显示150条关键字查询公告
                payloadDatakw = {
                            'categoryCode': "ZcyAnnouncement2",
                            'keyword': f'{val}',
                            'pageNo': f'{i}',
                            'pageSize': 15
                }
                names["res%s" % i] = post_url(payloadDatakw)
                final_datas = clear_data(names["res%s" % i])
                j = (i-1)*15+1
                for final_data in final_datas:
                    data = final_data['_source']
                    names["timeStamp_%s" % j] = int(data['publishDate']/1000)
                    # timeStamp_2 = int(data['bidOpeningTime']/1000)
                    names["timeArrays_%s" % j] = time.localtime(names["timeStamp_%s" % j])
                    # timeArrays_2 = time.localtime(timeStamp_2)
                    publishDate = time.strftime("%Y--%m--%d %H:%M:%S", names["timeArrays_%s" % j])
                    # bidOpeningTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArrays_2)
                    # districtName = data['districtName']
                    title = (data['title'])
                    f_url = (base_url + data['url'])
                    # print(title)
                    if title:
                        text.tag_config('link>'+f_url, underline=True)
                        text.insert('insert', "【"+publishDate+"】"+title+'\n'+'\n', 'link>'+f_url)
                        text.tag_bind('link>'+f_url, "<Double-Button-1>", lambda event, f_url = f_url: open_url(event, f_url))
                    else:
                        text.insert('insert', "加载完成！！！")

                    def open_url(event, f_url):
                        webbrowser.open(f_url, new=0)
                    j = j+1
                    frame2.update()
        
        def subscribe():
            # 文件操作
            var = entry.get()
            with open("subscribe_keyword.txt", "a+") as f:
                f.write(var+"\n")
            f.close()
            # 弹窗提示
            messagebox.showinfo(title="提示", message="订阅成功！")
        # 获取关键字
        def get_subword():
            text4.delete('0.0', 'end')
            lines = []
            with open("subscribe_keyword.txt", "r") as f:
                for line in f.readlines():
                    lines.append(line.strip('\n'))
                length = len(lines)
            f.close()
            for m in range(length):
                names["lb%s" % m] = tk.Button(frame3, text=lines[m], font=("URW Gothic L", 12, 'bold'))
                names["lb%s" % m].grid(row=1, column=m, padx=20, pady=20)
                if lines[m]:
                    for i in range(1, 11):   # 最多显示150条订阅公告
                        payloadDatakw = {
                            'categoryCode': "ZcyAnnouncement2",
                            'keyword': f'{lines[m]}',
                            'pageNo': f'{i}',
                            'pageSize': 15
                        }
                        names["res%s" % i] = post_url(payloadDatakw)
                        final_datas = clear_data(names["res%s" % i])
                        j = (i - 1) * 15 + 1
                        for final_data in final_datas:
                            data = final_data['_source']
                            names["timeStamp_%s" % j] = int(data['publishDate'] / 1000)
                        # timeStamp_2 = int(data['bidOpeningTime']/1000)
                            names["timeArrays_%s" % j] = time.localtime(names["timeStamp_%s" % j])
                        # timeArrays_2 = time.localtime(timeStamp_2)
                            publishDate = time.strftime("%Y--%m--%d %H:%M:%S", names["timeArrays_%s" % j])
                        # bidOpeningTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArrays_2)
                        # districtName = data['districtName']
                            title = (data['title'])
                            f_url = (base_url + data['url'])
                        # print(title)
                            if title:
                                text4.tag_config('link>' + f_url, underline=True)
                                text4.insert('insert', "【" + publishDate + "】" + title + '\n' + '\n', 'link>' + f_url)
                                text4.tag_bind('link>' + f_url, "<Double-Button-1>",
                                        lambda event, f_url=f_url: open_url(event, f_url))
                            else:
                                text.insert('insert', "加载完成！！！")
                            def open_url(event, f_url):
                                webbrowser.open(f_url, new=0)
                            j = j + 1
                            frame3.update()
                else:
                    break
        
        key_word = tk.Label(frame2, text='请输入关键词：', font=("URW Gothic L", 12, 'bold'))
        key_word.grid(row=0, sticky=W, padx=20, pady=20)
        kw = tk.StringVar()
        # 输入框 获取关键字
        entry = tk.Entry(frame2, width=40, textvariable=kw)
        entry.grid(row=0, column=1, sticky=E)
        # 搜索按钮
        btn1 = tk.Button(frame2, text="搜索", width=15, command=func)
        btn1.grid(row=0, column=2, sticky=E, padx=20, pady=20)
        # 订阅按钮
        btn2 = tk.Button(frame2, text="订阅", width=15, command=subscribe)
        btn2.grid(row=0, column=3, sticky=E, padx=20, pady=20)
        # 提交按钮绑定回车
        window.bind("<Return>", lambda event=None: btn1.invoke())
        text = tk.Text(frame2, width=161, height=43, font=("URW Gothic L", 13))
        # 滚动条，可有可无        
        # scroll = tk.Scrollbar()
        # scroll.pack(side=RIGHT, fill=Y)
        # scroll.config(command=text.yview)
        # text.config(yscrollcommand=scroll.set)
        text.grid(row=2, columnspan=50, sticky=W, padx=20, pady=20)
        
        '''
        **********第三页订阅功能**********
        '''
        frame3 = tk.Frame(tab)
        tab.add(frame3, text="订阅信息")
        counts = []
        with open("subscribe_keyword.txt", "r") as f:
            for count in f.readlines():
                counts.append(count.strip('\n'))
            lens = len(counts)
        f.close()
            
        lable1 = tk.Label(frame3, text="已订阅数："+str(lens), font=("URW Gothic L", 12, 'bold'))
        lable1.grid(row=0, sticky=W, padx=20, pady=20)
        btn3 = tk.Button(frame3, text="查看已订阅", width=15, command=get_subword)
        btn3.grid(row=0, column=1, sticky=E, padx=20, pady=20)
        # 订阅信息文本框
        text4 = tk.Text(frame3, width=161, height=43, font=("URW Gothic L", 13))
        text4.grid(row=6, columnspan=50, sticky=W, padx=20, pady=20)

        tab.pack(expand=True, fill=tk.BOTH)
        window.mainloop()


if __name__ == "__main__":
    tbm = TestBenchMaker()
    tbm.initialGUI()
